/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.broker.dao;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Future;

import org.ourgrid.common.interfaces.Worker;
import org.ourgrid.common.spec.worker.WorkerSpec;

import br.edu.ufcg.lsd.commune.Application;
import br.edu.ufcg.lsd.commune.container.servicemanager.dao.DAO;
import br.edu.ufcg.lsd.commune.identification.DeploymentID;
import br.edu.ufcg.lsd.commune.identification.ServiceID;

/**
 * Maintains information about the current 
 * workers providers of this Broker.
 * 
 */
public class WorkerDAO extends DAO {

	private Future<?> schedulerFuture;
	private Map<DeploymentID, Worker> workers;
	private Map<DeploymentID, WorkerSpec> workerSpecs;
	private Map<ServiceID, String> workersPublicKeys;
	
	public WorkerDAO(Application application) {
		super(application);
		this.workers = new LinkedHashMap<DeploymentID, Worker>();
		this.workerSpecs = new LinkedHashMap<DeploymentID, WorkerSpec>();
		this.workersPublicKeys = new LinkedHashMap<ServiceID, String>();
	}
	
	public void addWorker(DeploymentID deploymentID, Worker worker, WorkerSpec workerSpec) {
		this.workers.put(deploymentID, worker);
		this.workerSpecs.put(deploymentID, workerSpec);
		this.workersPublicKeys.put(deploymentID.getServiceID(), deploymentID.getServiceID().getPublicKey());
		
	}
	
	public void removeWorker(DeploymentID deploymentID) {
		this.workers.remove(deploymentID);
		this.workerSpecs.remove(deploymentID);
	}
	
	public String getWorkerPublicKey(ServiceID serviceID) {
		return this.workersPublicKeys.get(serviceID);
	}
	
	public Worker getWorker(DeploymentID deploymentID) {
		return this.workers.get(deploymentID);
	}
	
	public WorkerSpec getWorkerSpec(DeploymentID deploymentID) {
		return this.workerSpecs.get(deploymentID);
	}
	
	public void setSchedulerFuture(Future<?> schedulerFuture) {
		this.schedulerFuture = schedulerFuture;		
	}

	public void cancelSchedulerFuture() {
		if (schedulerFuture != null) {
			schedulerFuture.cancel(true);
		}	
	}
	
	public boolean isSchedulerActionActive() {
		return this.schedulerFuture != null && 
			!this.schedulerFuture.isCancelled() && 
			!this.schedulerFuture.isDone();
	}
	
}
